//
//  UIPlayer.m
//  MGPolymerAdSDK_Example
//
//  Created by 虞嘉伟 on 2025/1/7.
//  Copyright © 2025 790879770@qq.com. All rights reserved.


#import "UIPlayer.h"

@implementation UIPlayer

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    self.playerLayer.frame = self.bounds;
}
- (void)setMediaURL:(NSString *)mediaURL {
    if (![_mediaURL isEqualToString:mediaURL]) {
        _mediaURL = mediaURL;
        
        NSURL *url = [NSURL fileURLWithPath:mediaURL];
        //初始化播放器对象
        AVPlayer *avplayer = [AVPlayer playerWithURL:url];
        
        if (self.playerLayer) {
            self.playerLayer.player = avplayer;
        } else {
            //显示画面
            AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer:avplayer];
            
            //视频填充模式
            layer.videoGravity = AVLayerVideoGravityResizeAspect;
            
            [self.layer addSublayer:layer];
            
            self.avplayer = avplayer;
            self.playerLayer = layer;
        }
    }
}

// 播放
- (void)play {
    if (self.avplayer.rate == 0) {
        [self.avplayer play];
    }
}

//暂停
- (void)pause {
    if (self.avplayer.rate != 0) {
        [self.avplayer pause];
    }
}

@end
